package com.ts.task;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ts.mapper.dataOne.TransitMapper;
import com.ts.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ts.utils.SignBuilder.genSignUrl;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
@ComponentScan
public class ProfessionalTaskScheduler {

    @Autowired
    private TransitMapper transitMapper;

    /**
     * 背景核查定时任务
     */
    //@Scheduled(cron = "* * 1 * * ?")
    public void checkTask(){
        try {
            long l = System.currentTimeMillis();
            int i = 1;
            //1.取到行业监管人员名单
            List<String> isList = transitMapper.getIndustryStaffList();
            String ipPort = PropertyUtils.getProp("bigdata_ip_port");
            String token = PropertyUtils.getProp("bigdata_zdrybjhc_token");
            String url = PropertyUtils.getProp("bigdata_zdrybjhc_url");
            for (String zjhm : isList) {
                long l1 = System.currentTimeMillis();
                //1.生成apigs_ca_sign
                Map<String, Object> queryParams = Maps.newHashMap();
                queryParams.put("sfzh",zjhm);
                String sign = createSign(token,url,queryParams);

                //2.发送请求，取回结果集，并解析第一组数据入库
                String completeUrl = ipPort + genSignUrl(url, queryParams);
                String responseStr = HttpClientUtil.sendRequest(sign,completeUrl,token);

                List<List<String>> lists = analysisZdryBjhcmx(responseStr);
                Map<String,Object> params = new HashMap<String,Object>();
                //3,.非重点人员字段填充无异常，更新更新时间。重点人员填充异常类型，填充更新时间
                if(null != lists){
                    String rylb = "";
                    //2.结果入库
                    for (List<String> information : lists) {
                        String iRylb = information.get(33);
                        if(!rylb.contains(iRylb)){
                            rylb = rylb + iRylb + ",";
                        }
                    }
                    if(rylb.length() > 0){
                        params.put("rylb",rylb.substring(0, rylb.length() - 1));
                    }
                }else {
                    params.put("rylb","经核查无异常");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                params.put("zjhm",zjhm);
                params.put("checkTime",System.currentTimeMillis());
                params.put("updateTime",sdf.format(new Date()));
                transitMapper.updateIndustryStaff(params);
                params.put("id", StringUtil.getUUID());
                params.put("ckeckType","industry_staff");
                //4.将核查记录记录到日志表中（日志表要标记核查的是哪张表）
                transitMapper.insertBackgroundCheckLog(params);
                System.out.println("核查第【"+ i + "】个人，身份证[" + zjhm + "]耗时："+(System.currentTimeMillis() - l1));
                i++;
            }
            System.out.println("总耗时"+ (System.currentTimeMillis() - l));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成sign
     */
    public String createSign(String token , String url , Map<String,Object> queryParams){

        SignBuilder signBuilder = SignBuilder.build()
                .url(genSignUrl(url, queryParams))
                .token(token)
                .signType(HmacSignTypeEnum.HMAC_SHA256);

        return signBuilder.sign();
    }

    /**
     * 解析重点人员背景核查请求返回值
     */
    public List<List<String>> analysisZdryBjhcmx(String responseStr){

        //1.解析json
        JSONObject jsonObject =JSONObject.parseObject(responseStr);
        Map<String,Object> data = (Map<String, Object>) jsonObject.get("data");
        Map<String,Object> result = (Map<String, Object>) data.get("result");
        List<List<String>> values = (List<List<String>>) result.get("values");
        if(null != values && values.size() > 0){
            return values;
        }
        return null;
    }

    public static void main(String[] args) {
    }
}
